import { Suspense } from "react"
import { Shell } from "@/components/shell"
import { DataTableSkeleton } from "@/components/data-table/data-table-skeleton"
import {
  getGeneralContracts,
  getGeneralContractStatusCounts,
  getGeneralContractCategoryCounts,
  getVendors
} from "@/lib/general-contracts/service"
import { GeneralContractsTable } from "@/lib/general-contracts/main/general-contracts-table"
import { getValidFilters } from "@/lib/data-table"
import { type SearchParams } from "@/types/table"
import { InformationButton } from "@/components/information/information-button"

export const metadata = {
  title: "일반계약 관리",
  description: "일반계약을 생성하고 관리할 수 있습니다.",
}

interface IndexPageProps {
  searchParams: Promise<SearchParams>
}

// searchParams 파싱을 위한 기본 파서 함수
function parseSearchParams(searchParams: SearchParams) {
  const page = Number(searchParams.page) || 1
  const perPage = Number(searchParams.per_page) || 10
  const sort = searchParams.sort 
    ? Array.isArray(searchParams.sort) 
      ? searchParams.sort.map((s: string) => {
          const [id, desc] = s.split('.')
          return { id, desc: desc === 'desc' }
        })
      : [{ id: searchParams.sort.split('.')[0], desc: searchParams.sort.split('.')[1] === 'desc' }]
    : [{ id: "registeredAt", desc: true }]
  
  return {
    page,
    perPage,
    sort,
    filters: [],
    contractNumber: searchParams.contractNumber as string,
    name: searchParams.name as string,
    status: searchParams.status as string,
    category: searchParams.category as string,
    type: searchParams.type as string,
    vendorId: searchParams.vendorId ? Number(searchParams.vendorId) : undefined,
    createdAtFrom: searchParams.createdAtFrom as string,
    createdAtTo: searchParams.createdAtTo as string,
    signedAtFrom: searchParams.signedAtFrom as string,
    signedAtTo: searchParams.signedAtTo as string,
    search: searchParams.search as string,
  }
}

export default async function GeneralContractsPage(props: IndexPageProps) {
  // ✅ searchParams 파싱
  const searchParams = await props.searchParams
  const search = parseSearchParams(searchParams)
  
  const validFilters = getValidFilters(search.filters)

  // ✅ 모든 데이터를 병렬로 로드
  const promises = Promise.all([
    getGeneralContracts({
      ...search,
      filters: validFilters,
    }),
    getGeneralContractStatusCounts(),
    getGeneralContractCategoryCounts(),
    getVendors(),
  ])

  return (
    <Shell className="gap-4">
      {/* ═══════════════════════════════════════════════════════════════ */}
      {/* 페이지 헤더 */}
      {/* ═══════════════════════════════════════════════════════════════ */}
      <div className="flex items-center justify-between space-y-2">
        <div className="flex items-center justify-between space-y-2">
          <div>
            <div className="flex items-center gap-2">
              <h2 className="text-2xl font-bold tracking-tight">
                일반계약 관리
              </h2>
              <InformationButton pagePath="evcp/general-contracts" />
            </div>
            <p className="text-muted-foreground">
              일반계약을 생성하고 관리할 수 있습니다. 계약 상세정보, 품목정보, 납품확인서 등을 관리할 수 있습니다.
            </p>
          </div>
        </div>
      </div>

      {/* ═══════════════════════════════════════════════════════════════ */}
      {/* 메인 테이블 */}
      {/* ═══════════════════════════════════════════════════════════════ */}
      <Suspense
        fallback={
          <DataTableSkeleton
            columnCount={15}
            searchableColumnCount={3}
            filterableColumnCount={4}
            cellWidths={["10rem", "8rem", "12rem", "15rem", "10rem", "8rem"]}
            shrinkZero
          />
        }
      >
        <GeneralContractsTable promises={promises} />
      </Suspense>
    </Shell>
  )
}
